package com.xoms.util.web;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * @author chengl
 */
public class HttpUtil {

	private static final Logger logger = Logger.getLogger(HttpUtil.class);
	private static final CloseableHttpClient httpclient = HttpClients.createDefault();
	private static final String userAgent = "Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.87 Safari/537.36";

	/**
	 * 发送HttpGet请求
	 * 
	 * @param url
	 *            请求地址
	 * @return 返回字符串
	 */
	public static String sendGet(String url) {
		String result = null;
		CloseableHttpResponse response = null;
		try {
			HttpGet httpGet = new HttpGet(url);
			httpGet.setHeader("User-Agent", userAgent);
			response = httpclient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				result = EntityUtils.toString(entity);
			}
		} catch (Exception e) {
			logger.error("处理失败，" + e);
			e.printStackTrace();
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return result;
	}

	/**
	 * 发送HttpPost请求，参数为map
	 * 
	 * @param url
	 *            请求地址
	 * @param map
	 *            请求参数
	 * @return 返回字符串
	 */
	public static String sendPost(String url, Map<String, String> map) {
		// 设置参数
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			formparams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
		}
		// 编码
		UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, Consts.ISO_8859_1);
		// 取得HttpPost对象
		HttpPost httpPost = new HttpPost(url);
		// 防止被当成攻击添加的
		httpPost.setHeader("User-Agent", userAgent);
		// 参数放入Entity
		httpPost.setEntity(formEntity);
		CloseableHttpResponse response = null;
		String result = null;
		try {
			// 执行post请求
			response = httpclient.execute(httpPost);
			// 得到entity
			HttpEntity entity = response.getEntity();
			// 得到字符串
			result = EntityUtils.toString(entity);
		} catch (IOException e) {
			logger.error(e.getMessage());
		} finally {
			if (response != null) {
				try {
					response.close();
				} catch (IOException e) {
					logger.error(e.getMessage());
				}
			}
		}
		return result;
	}
	
	
	
	/**
	 * 可以解决中文提交乱码问题的提交方式
	 * @param url
	 * @param value
	 * @return
	 * @throws IOException
	 */
	public static String httpUrlConn(String url, String value) throws IOException{
		BufferedReader in =null;
		HttpURLConnection conn = null;
		StringBuffer buffer = new StringBuffer();
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			conn = (HttpURLConnection) realUrl.openConnection();
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			conn.getOutputStream().write(value.getBytes("UTF-8"));
			// flush输出流的缓冲
			conn.getOutputStream().flush();
	
			if (conn.getResponseCode() == 200) {
				// 定义BufferedReader输入流来读取URL的响应
				in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
				String line;
				while ((line = in.readLine()) != null) {
					buffer.append(line);
				}
				
				String result = buffer.toString();
				buffer.insert(0, "_____"); 
				buffer.insert(0, value); 
				return result;
			}else{
				throw new IOException("POST响应异常码："+conn.getResponseCode());
			}
		}catch(IOException e){
			throw e;
		}finally{
			if (in != null) {
				in.close();
			}
			if(conn != null){
				conn.disconnect();
			}
		}
	}
	
	
	public static void main(String[] args) {
		Map<String, String> map = new HashMap<>();
		map.put("str", "123");
		sendGet("192.168.1.168:6090?string=12312");
	}
}